package com.btex.app.pager;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.btex.app.Config;
import com.btex.app.LoginActivity;
import com.btex.app.OTCBuyActivity;
import com.btex.app.R;
import com.btex.app.adapter.OTCBuyAdapter;
import com.btex.app.entity.OTCBuyAndSellOrderBean;
import com.btex.app.entity.OTCUserInfo;
import com.btex.app.tools.MicroAVLIDialog;
import com.btex.app.tools.OTCRealNameDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * @author zy zhangyi <zhangyi, 1104745049@QQ.com
 * @version v1.0
 * @project study1
 * @Description
 * @encoding UTF-8
 * @date 2018/8/13
 * @time 下午2:29
 * @修改记录 <pre>
 * 版本       修改人         修改时间         修改内容描述
 * --------------------------------------------------
 * <p>
 * --------------------------------------------------
 * </pre>
 */

public class OTCBuyFragment extends Fragment {


    @BindView(R.id.otc_recy)
    RecyclerView mOtcRecy;
    Unbinder unbinder;
    @BindView(R.id.otc_fragment_recy)
    SwipeRefreshLayout mOtcFragmentRecy;
    private OTCBuyAdapter mOtcBuyAdapter;
    public String otcType = "USDT_CNY";


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View inflate = inflater.inflate(R.layout.otc_fragment, null);
        unbinder = ButterKnife.bind(this, inflate);
        if (!EventBus.getDefault().isRegistered(this)) {//加上判断
            EventBus.getDefault().register(this);
        }
        return inflate;

    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        //初始化数据
        initAdapter();
        initData();


        mOtcFragmentRecy.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                initData();
            }
        });

    }

    private void initAdapter() {
        mOtcRecy.setLayoutManager(new LinearLayoutManager(getActivity()));
        mOtcBuyAdapter = new OTCBuyAdapter(null, getActivity());
        mOtcBuyAdapter.bindToRecyclerView(mOtcRecy);
        mOtcRecy.setAdapter(mOtcBuyAdapter);
    }


    private void initData() {


        int num = (int) ((Math.random() * 9 + 1) * 100000);
        mOtcFragmentRecy.setRefreshing(true);

        OkGo.<String>get(Config.GET_OTC_ORDERS + "&rnd=" + String.valueOf(num)).tag(this).params("pair", otcType).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                mOtcFragmentRecy.setRefreshing(false);

                String result = response.body().toString();
                Log.i("klqwdqwidq", result);
                try {
                    JSONObject jsonObject = new JSONObject(result);

                    String code = jsonObject.getString(Config.KEY_CODE);

                    if ("1".equals(code)) {

                        Gson gson = new Gson();
                        OTCBuyAndSellOrderBean otcBuyAndSellOrderBean = gson.fromJson(result, OTCBuyAndSellOrderBean.class);
                        List<OTCBuyAndSellOrderBean.DataBean.AsksBean> bids = otcBuyAndSellOrderBean.getData().getAsks();
                        setData(bids);

                    }

                } catch (JSONException e) {
                    e.printStackTrace();

                }

            }

            @Override
            public void onFinish() {
                super.onFinish();
                mOtcFragmentRecy.setRefreshing(false);

            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                mOtcFragmentRecy.setRefreshing(false);

            }
        });

    }

    private void setData(List<OTCBuyAndSellOrderBean.DataBean.AsksBean> asks) {

        if (mOtcBuyAdapter != null) {

            if (asks.size() <= 0) {

                if (mOtcRecy != null) {

                    asks.clear();
                    mOtcBuyAdapter.replaceData(asks);
                    mOtcBuyAdapter.setEmptyView(R.layout.otc_order_empty);


                }

            } else {

                mOtcBuyAdapter.replaceData(asks);
            }

        }

        mOtcBuyAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                OTCBuyAndSellOrderBean.DataBean.AsksBean asksBean = (OTCBuyAndSellOrderBean.DataBean.AsksBean) adapter.getData().get(position);

                getUserInfo(asksBean);
            }
        });

    }


    private void getUserInfo(final OTCBuyAndSellOrderBean.DataBean.AsksBean asksBean) {
        final MicroAVLIDialog microAVLIDialog = new MicroAVLIDialog(getActivity());
        microAVLIDialog.show();
        int num = (int) ((Math.random() * 9 + 1) * 100000);

        OkGo.<String>get(Config.URL_MY_INFO + "rnd=" + String.valueOf(num)).tag(this).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String reuslt = response.body().toString();
                if (microAVLIDialog != null) {
                    microAVLIDialog.dismiss();
                }
                try {
                    JSONObject jsonObject = new JSONObject(reuslt);
                    if (jsonObject.getString(Config.KEY_CODE).equals("1")) {
                        Gson gson = new Gson();
                        OTCUserInfo otcUserInfo = gson.fromJson(reuslt, OTCUserInfo.class);
                        String prove_level = otcUserInfo.getData().getProve_level();

                        if (prove_level.equals("C0") || prove_level.equals("C1")) {
//
                            new OTCRealNameDialog(getActivity(), prove_level).show();
                            return;
                        }

                        if (prove_level.equals("C2")) {
                            startActivity(new Intent(getActivity(), OTCBuyActivity.class).putExtra("data", (Serializable) asksBean));
                            return;
                        }

                    } else if (jsonObject.getString(Config.KEY_CODE).equals("-2")) {
                        startActivity(new Intent(getActivity(), LoginActivity.class));
                    }

                } catch (JSONException e) {
                    e.printStackTrace();

                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                if (microAVLIDialog != null) {
                    microAVLIDialog.dismiss();
                }

            }
        });

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();

        if (EventBus.getDefault().isRegistered(this))//加上判断
            EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void OTCBuyFragment(String event) {
        otcType = event;
        initData();

    }


    @Override
    public void onPause() {
        super.onPause();
        OkGo.getInstance().cancelTag(this);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        OkGo.getInstance().cancelTag(this);
    }
}
